﻿using AuthorityManagement.Model;
using AuthorityManagement.Model.Dto.MenuDto;
using AutoMapper;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static AuthorityManagement.Controllers.TreeMenuController;
using static AuthorityManagement.Helper.RuturnHelper;

namespace AuthorityManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MenuController : ControllerBase
    {
        private readonly ISqlSugarClient _Db;
        private IMapper _mapper;
        public MenuController(ISqlSugarClient db, IMapper mapper)
        {
            _Db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取菜单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic>GetMenuId(string id)
        {
            var data = await _Db.Queryable<Menu>().Where(it => it.Id == id).Select(it => new MenuInfoOutPut() {Id=it.Id, MenuCode = it.MenuCode, MenuName = it.MenuName, ParentId = it.ParentId, URL = it.URL, Status = it.Status, Type = it.Type }).FirstAsync();
            return data;
        }

        /// <summary>
        /// 获取树型菜单.
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTreeList")]
        [AllowAnonymous]
        public async Task<dynamic> GetTreeList()
        {
            var data = await _Db.Queryable<Menu>().ToTreeAsync(it => it.Children, it => it.ParentId, -1);
            return data;
        }

        [HttpPost("Create")]
        public async Task<dynamic> Create([FromBody] MenuCrInput input)
        {
            var data = input.Adapt<Menu>();
            data.Id = Guid.NewGuid().ToString();
            //if (input.Type == "page")
            //{
            //    data.URL = "@/views/" + input.URL;
            //}
            var isOk = await _Db.Insertable(data).ExecuteCommandAsync();
            if (isOk > 0)
            {
                return RR.Success("添加成功！");
            }
            else
            {
                return RR.Error("添加失败！");
            }
        }

        [HttpPut("")]
        public async Task<dynamic> Update(string id,[FromBody] MenuUpInput input)
        {
            var data = input.Adapt<Menu>();
            if (input.Type == "page")
            {
                data.URL = "@/views/" + input.URL;
            }
            var isOk = await _Db.Updateable(data).UpdateColumns(it => new Menu()
            {
                Id = it.Id,
                MenuCode = it.MenuCode,
                ParentId = it.ParentId,
                MenuName = it.MenuName,
                Type = it.Type,
                URL = it.URL,
                Status = it.Status,

            }).ExecuteCommandAsync();
            if (isOk > 0)
            {
                return RR.Success("编辑成功！");
            }
            else
            {
                return RR.Error("编辑失败！");
            }
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("")]
        public async Task<dynamic> DeleteMenu(string id)
        {
            var isOk = await _Db.Deleteable<Menu>().Where(it => it.Id == id).ExecuteCommandAsync();
            if (isOk > 0)
            {
                return RR.Success("删除成功！");
            }
            else
            {
                return RR.Error("删除失败！");
            }
        }

        [HttpGet("GetMenuSelectAsync")]
        public async Task<List<MenuSelectDto>> GetMenuSelectAsync()
        {
            var menulist = await _Db.Queryable<Menu>().ToListAsync();
            List<MenuSelectDto>tree=new List<MenuSelectDto>();
            foreach (var item in menulist)
            {
                tree.Add(_mapper.Map<MenuSelectDto>(item));
            }
            var Treelist = GetMenuSelect(tree, "-1");
            return Treelist;
        }
        private static List<MenuSelectDto> GetMenuSelect(List<MenuSelectDto>list ,string pid)
        {
            List<MenuSelectDto> tree = new List<MenuSelectDto>();
            var children = list.Where(m => m.ParentId == pid).ToList();
            if (children.Count > 0)
            {
                for (var i = 0; i < children.Count; i++)
                {
                    MenuSelectDto itemMenu = new MenuSelectDto();
                    //itemMenu.item=children[i];
                    itemMenu.Id = children[i].Id;
                    itemMenu.Name = children[i].Name;
                    itemMenu.ParentId = children[i].ParentId;
                    itemMenu.Children = GetMenuSelect(list, children[i].Id);
                    tree.Add(itemMenu);
                }
            }
            return tree;
        }

        public class MenuSelectDto
        {
            public string Id { get; set; }
            /// <summary>
            /// 父级id
            /// </summary>
            public string ParentId { get; set; }
            public string Name { get; set; }
            public List<MenuSelectDto> Children { get; set; } = new List<MenuSelectDto>();
        }
    }
}
